<template>
  <FlowPanel class="contour" :width="240">
    <div slot="header" class="header">
      <span style="font-size: 16px;color: #333333; font-weight: bold; margin-left: 13px">等高线生成</span>
      <a-icon type="close" :style="{float:'right',margin:'8px'}"/>
    </div>
    <a-row>
      <a-col :span="12" :style="{'text-align':'center','font-size':'20px'}">
        <a-icon type="edit"/>
      </a-col>
      <a-col :span="12" :style="{'text-align':'center','font-size':'20px'}">
        <a-icon @click="drawRect" type="pie-chart"/>
      </a-col>
    </a-row>
    <a-row>
      <a-button>清除</a-button>
      <a-button @click="renderContourLine">生成</a-button>
    </a-row>
  </FlowPanel>
</template>

<script>
  import FlowPanel from "../common/FlowPanel";
  import Earth from '@/js/earth/earth'

  import ElevationGradient from '@/js/contourline/ElevationGradientImageryProvider'

  export default {
    name: "ContourLine",
    components: {FlowPanel},
    data() {
      return {
        drawing: false,
        tip: null,
        handler: null,
        positions: [],
        rectEntity: null
      }
    },
    computed: {},
    created() {
    },
    mounted() {
      this.handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
      this.drawEvent();
    },
    methods: {

      /**绘制轨迹事件 */
      drawEvent() {
        let that = this;
        this.handler.setInputAction(event => {
          if (!that.drawing) {
            return false;
          }
          let param = Earth.parsePosition(event.position, viewer);
          if (param && param.cartesian3) {
            let cartesian3 = param.cartesian3;
            if (that.positions.length == 0) {
              that.positions.push(cartesian3.clone());
              let dynamicRect = new Cesium.CallbackProperty(() => {
                return Cesium.Rectangle.fromCartesianArray(that.positions);
              }, false);
              that.rectEntity = viewer.entities.add({
                rectangle: {
                  coordinates: dynamicRect,
                  material: Cesium.Color.fromBytes(0, 255, 255, 50),
                  outline: 3,
                },
              });
            } else if (this.positions.length == 2) {
              that.positions.pop();
              that.positions.push(cartesian3);
              that.drawing = false;
            }
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        this.handler.setInputAction(event => {
          if (!that.drawing) {
            return false;
          }
          let param = Earth.parsePosition(event.endPosition, viewer);
          if (param && param.cartesian3 && that.rectEntity) {
            let cartesian3 = param.cartesian3;
            if (that.positions.length > 1) {
              that.positions.pop();
            }
            that.positions.push(cartesian3);
          }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // this.handler.setInputAction(event => {
        //   this.toggleTip(false);
        //   this.drawing = false;
        // }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      },

      drawRect() {
        if (this.rectEntity) {
          viewer.entities.remove(this.rectEntity);
          this.rectEntity = null;
          this.drawing = false;
          this.positions.length = 0;
        } else {
          this.drawing = true;
        }
      },

      renderContourLine() {
        let that = this;
        let terrainProvider = viewer.terrainProvider;
        let gradient = [
          {
            "color": {
              "red": 0,
              "green": 0,
              "blue": 0,
              "alpha": 0
            },
            "value": 600
          },
          {
            "color": {
              "red": 0,
              "green": 0,
              "blue": 1,
              "alpha": 0.5
            },
            "value": 600
          },
          {
            "color": {
              "red": 1,
              "green": 0,
              "blue": 0,
              "alpha": 0.5
            },
            "value": 1000
          },
          {
            "color": {
              "red": 0,
              "green": 0,
              "blue": 0,
              "alpha": 0
            },
            "value": 1000
          }
        ]

        let line = [];
        let dynamicPositions = new Cesium.CallbackProperty(() => {
          return line;
        }, false);
        viewer.entities.add({
          polyline: {
            positions: dynamicPositions,
            material: Cesium.Color.fromBytes(255, 0, 0, 255),
            width: 3,
            clampToGround: true,
          },
        });
        let pos = [];
        let rectangle = this.rectEntity.rectangle;
        let count = 0;
        const valueSampler = (positions, level) => {
          if(!rectangle){
            return ;
          }
          let arr = [];
          for (let i = 0; i < positions.length; i++) {
            let p = positions[i];
            let bar =   rectangle._coordinates.getValue()
            if(Cesium.Rectangle.contains(bar, p))  {
              arr.push(p);
            }
          }
          if(arr.length==0){
            return;
          }
          Cesium.sampleTerrainMostDetailed(terrainProvider, positions).then((sampledPositions) => {
            pos = pos.concat(sampledPositions);
            let hmap = new Map;
            for (let i = 0; i < pos.length; i++) {
              let one = pos[i];
              let cartesian3 = Cesium.Cartographic.toCartesian(one);
              let height = Math.floor(one.height);
              if (hmap.has(height)) {
                let foo = hmap.get(height);
                foo.push(cartesian3);
                hmap.set(height, foo)
              } else {
                hmap.set(height, [cartesian3])
              }
            }
            count ++ ;
            if(count>10){
              that.renderLine(hmap);
            }
            sampledPositions.map(position => position.height)
          })
        };

        const imageryLayer = viewer.imageryLayers.addImageryProvider(new ElevationGradient({
          valueSampler,
          readyPromise: terrainProvider.readyPromise,
          majorContour: 25,
          minorContour: 5,
          gradient: gradient
        }));
        // imageryLayer.alpha = 1.0;
      },

      renderLine(hmap) {
        let entities = viewer.entities;
        let needremove = [];
        let sources = entities._entities._array;
        for (let i = 0; i < sources.length; i++) {
          let one = sources[i];
          if (one && one._catalog == 'contourline') {
            needremove.push(one);
          }
        }
        for (let i = 0; i < needremove.length; i++) {
          entities.remove(needremove[i], true);
        }


        let heights = [];
        hmap.forEach((value, key) => {
           heights.push(key);
        });

        heights = heights.ascSort();
        let min = heights[0];
        let max = heights[heights.length - 1];

        let h = min;
        while (h < max) {
          let pos = null;
           hmap.forEach((value, key) => {
            if (Math.abs(key - h) < 1) {
              pos =  value;
            }
          });

          if (pos && pos.length>20) {
            // viewer.entities.add({
            //   polyline: {
            //     positions: pos,
            //     material:  Cesium.Color.fromRandom(),
            //     width: 1,
            //     clampToGround: true,
            //   },
            //   catalog: 'contourline'
            // });

            let  color =  Cesium.Color.fromRandom();
            for (let i = 0; i < pos.length; i++) {
              viewer.entities.add({
                position:pos[i],
                point: {
                  pixelSize:5,
                  color: color,
                  },
                  catalog: 'contourline'
                });
            }

          }
          h += 100;
        }

        console.log(h);
      },


      toggleTip(isShow, text, e) {
        if (!this.tip) {
          this.tip = document.createElement('div');
          this.tip.style.position = 'fixed';
          this.tip.style.backgroundColor = '#FFFFFF';
          this.tip.style.fontFamily = '宋体';
          this.tip.style.fontSize = '10px';
          this.tip.style.padding = '5px';
          this.tip.style.color = '#A8A8A8';
          document.body.appendChild(this.tip);
        }
        if (isShow) {
          this.tip.style.left = e.endPosition.x + 15 + 'px';
          this.tip.style.top = e.endPosition.y + 15 + 'px';
          this.tip.innerText = text;
          this.tip.style.display = 'block';
        } else {
          this.tip.style.display = 'none';
        }
      },
    },
    beforeDestroy() {
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    }
  }
</script>

<style scoped lang="less">
  .contour {
    position: absolute;
    z-index: 99;
    top: 80px;
    right: 20px;

    .head {
      /*height: 35px;*/
    }

  }
</style>